package sort;



/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yi
 * Date: 2024-07-30
 * Time: 9:53
 */
public class MergeSort {

    //非递归思路
    public static void sort(int[] array) {
        int gap = 1;
        while (gap < array.length) {
            for (int i = 0; i < array.length; i += 2*gap) {
                int left = i;
                int mid = left + gap - 1;
                int right = mid + gap;
                if(mid >= array.length) {
                    mid = array.length - 1;
                }
                if(right >= array.length) {
                    right = array.length - 1;
                }
                merge(array,left,right,mid);
            }
            gap *= 2;
        }
    }
    //递归思路
    /*public static void sort(int[] array) {
        int left = 0;
        int right = array.length-1;
         recursion(array,left,right);
    }

    private static void recursion(int[] array, int left, int right) {
        int mid = (left+right) / 2;
        if(left >= right) return;
        recursion(array,left,mid);
        recursion(array,mid+1,right);
        merge(array,left,right,mid);
    }*/

    //归并操作
    private static void merge(int[] array, int left, int right, int mid) {
        int tmp = left;
        int s1 = left;
        int s2 = mid+1;
        int[] tmpArr = new int[right-left+1];
        int k = 0;

        //证明两个区间都有元素
        while (s1 <= mid && s2 <= right) {
            if(array[s2] <= array[s1]) {
                tmpArr[k++] = array[s2++];
            }else {
                tmpArr[k++] = array[s1++];
            }
        }
        while (s1 <= mid) {
            tmpArr[k++] = array[s1++];
        }
        while (s2 <= right) {
            tmpArr[k++] = array[s2++];
        }
        //走到这里这个区间的数组已经有序
        for (int i = 0; i < tmpArr.length; i++) {
            array[tmp++] = tmpArr[i];
        }
    }
}